//工具类
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatDate(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

String.prototype.trim = function () {
  return this.replace(/(^\s*)|(\s*$)/g, '');
}

String.prototype.isEmpty = function () {
  return this.trim() == '';
}

function limitScreenSize(that){
  var res = wx.getSystemInfoSync()
  // 设备信息
  that.setData({
    windowHeight: res.windowHeight,
    windowWidth: res.windowWidth,
    pixelRatio: res.pixelRatio
  });
}
function getAttacheUrls(attachment,app){
//附件url
    var that = this,
      attachUrls = []
    for (var i = 0; i < attachment.length; i++) {
      attachUrls.push(app.GLOBAL_CONFIG.commonUrl + attachment[i].resPath)
      console.log("图片路径 "+i+" :" + app.GLOBAL_CONFIG.commonUrl + attachment[i].resPath) 
    }
    return attachUrls
}

function getProjectAttacheUrls(attachment, app) {
//附件url
    var that = this,
      attachUrls = []
    for (var i = 0; i < attachment.length; i++) {
      attachUrls.push(app.GLOBAL_CONFIG.commonUrl + attachment[i].resource.resPath)
      console.log("图片路径 " + app.GLOBAL_CONFIG.commonUrl +  attachment[i].resource.resPath)
    }
    return attachUrls

}

/**
 * 检测网络状态
 */
function checkNetWorkStatus() {
  var statu = true
  wx.getNetworkType({
    success: function (res) {
      var networkType = res.networkType // 返回网络类型2g，3g，4g，wifi, none, unknown
      if (networkType == "none" || networkType == "unknown") {
        //没有网络连接
        statu = false
        wx.showModal({
          title: '提示',
          content: '无网络连接或未知网络类型,请检查您的网络设置',
          showCancel: false,
        })
      } 
    }
  })
  return statu
}
/**
 * post 请求
 */
function postRequest(url, cookie,appObj,selfObj, success, fail){
  wxRequest(url, 'post', cookie, appObj,selfObj, success, fail)
}
/**
 * get请求
 */
function getRequest(url, cookie, appObj,selfObj,success, fail){
  wxRequest(url, 'get', cookie, appObj,selfObj,success, fail)
}
/**
 * wx.request请求封装
 */
function wxRequest(url, method, cookie, appObj,selfObj,success,fail){
  var contentType = ''
  if (method == 'POST') {
     contentType = 'application/x-www-form-urlencoded'
  } else {
     contentType = 'application/json'
  }
  wx.request({
    url: url,
    method:method,
    header:{
      'Cookie': cookie,
      'Content-Type': contentType
    },
    success:function(res){
      if (res.statusCode == 200) {
        typeof success == "function" && success(res,selfObj);
      } else if (res.statusCode == 401) {    //登录态失效,重新登录并回调
       console.log("登录态失效，即将重新登录")
       loginAuto(url,method,contentType,appObj,selfObj,success,fail)

      } else if (res.statusCode == 416){
        wx.showToast({
          title: '您无访问权限！',
          icon: 'loading',
          duration: 2000,
        })
      }else {
        typeof fail == "function" && fail(res);
      }
    },
    fail:function(res){
      typeof fail == "function" && fail(res);
    }
  })
}

function loginAuto(url, method,contentType, appObj, selfObj, success, fail){
  //login用code去换取
 wx.login({
   success: function (res) {
     wx.getUserInfo({
       lang: "zh_CN",
       success: function (userRes) {
         //发起网络请求  
         wx.request({
           url: appObj.GLOBAL_CONFIG.commonUrl + "/project/miniprogram/getUserInfo.do",
           data: {
             code: res.code,
             encryptedData: userRes.encryptedData,//in case use these later
             iv: userRes.iv
           },
           header: {
             "Content-Type": "application/x-www-form-urlencoded"
           },
           method: 'POST',
           success: function (result) {
             if (result.data.errcode != undefined || result.data.errcode != null) {
               console.log("error and code is " + result.data.errcode)
               wx.showToast({
                 title: '操作失败请重试',
                 image:'../images/fail.png'
               })
             } else if (result.data.userStatus == "1") {
               let ybdUser = result.data.ybdUserData[0];
               let sessionId = result.data.seesionId;
               sessionId = 'JSESSIONID=' + sessionId;
               appObj.globalData.user = ybdUser;
               appObj.globalData.cookie = sessionId;
               wx.setStorageSync('user', ybdUser);
               wx.setStorageSync('cookie', sessionId);
               firstTarget(url, method, contentType, sessionId, selfObj, success, fail)
             } 
           },
           fail: function () {
             console.log("获取用户信息失败")
           }
         })
       }
     })
   }
 })
}

function firstTarget(url, method, contentType, cookie, selfObj, success, fail){
  wx.request({
    url: url,
    method: method,
    header: {
      'Cookie': cookie,
      'Content-Type': contentType
    },
    success: function (res) {
      if (res.statusCode == 200) {
        typeof success == "function" && success(res, selfObj);
      } else if (res.statusCode == 416) {
        wx.showToast({
          title: '您无访问权限！',
          icon: 'loading',
          duration: 2000,
        })
      } else {
        typeof fail == "function" && fail(res);
      }
    },
    fail: function (res) {
      typeof fail == "function" && fail(res);
    }
  })
}


function upload_file(url, cookie, filePath, name, formData, success, fail) {
  var that = this
  wx.uploadFile({
    url: url,
    filePath: filePath,
    name: name,
    header: {
      'Cookie': cookie,
      'content-type': 'multipart/form-data'
    },
    formData: formData, // HTTP 请求中其他额外的 form data
    success: function (res) {
      console.log(res);
      if (res.statusCode == 200 && !res.data.result_code) {
        typeof success == "function" && success(res);
      } else {
        typeof fail == "function" && fail(res);
      }
    },
    fail: function (res) {
      console.log(res);
      typeof fail == "function" && fail(res);
    }
  })
}


function documentOperate (url) {
  wx.showActionSheet({
    itemList: ['预览', '下载文件'],
    itemColor: "#f7982a",
    success: function (res) {
      if (!res.cancel) {
        if (res.tapIndex == 0) {//预览
          downloadFileAndView(url, 0);
        } else if (res.tapIndex == 1) {//下载
          downloadFileAndView(url, 1);
        }
      }
    }
  })
}

function imagePreview(current, urls) {
  wx.previewImage({
    current: current,
    urls: urls
  })
}


function downloadFileAndView(url, flag) {
  wx.downloadFile({
    url: url,
    success: function (res) {
      var filePath = res.tempFilePath
      if (flag == 0) {//预览
        openFile(filePath)
      } else if (flag == 1) {//保存到本地
        wx.saveFile({
          tempFilePath: filePath,
          success: function (res1) {
            var savedFilePath = res1.savedFilePath
            wx.showModal({
              title: '提示',
              content: '下载完成，是否打开文件？',
              success: function (res) {
                if (res.confirm) {
                  openFile(savedFilePath)
                } else {
                  return
                }
              }
            })
          }, fail: function () {
            wx.showToast({
              title: '下载失败，请稍后重试',
            })
          }
        })
      }
    },
    fail: function (err) {
      console.log("下载失败错误信息 " + err)
      wx.showToast({
        title: '操作失败，请稍后重试',
        image: '../../images/warning.png'
      })
    }
  })
}

function openFile(filePath) {
  wx.openDocument({
    filePath: filePath,
    success: function (res) {
      console.log('打开文档成功')
    },
    fail: function (res) {
      wx.showToast({
        title: '预览失败，请稍后重试',
      })
    }
  })
}


module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  getAttacheUrls: getAttacheUrls,
  getProjectAttacheUrls: getProjectAttacheUrls,
  limitScreenSize: limitScreenSize,
  postRequest: postRequest,
  getRequest: getRequest,
  checkNetWorkStatus: checkNetWorkStatus,
  upload_file: upload_file,
  documentOperate: documentOperate,
  imagePreview: imagePreview
}


